
/* 客户浏览器版本 */
if ($('html').hasClass('lt-ie8')) {
	var message = '<div class="alert alert-warning" style="margin-bottom:0;text-align:center;">';
	message += '对不起，您的浏览器版本太低，不能正常使用本站，请使用';
	message += '<a href="http://windows.microsoft.com/zh-CN/internet-explorer/downloads/ie" target="_blank">最新版IE浏览器</a>、';
	message += '<a href="https://www.google.com/intl/zh-CN/chrome/browser/" target="_blank">谷歌浏览器</a><strong>(推荐)</strong>、';
	message += '<a href="http://firefox.com.cn/download/" target="_blank">Firefox浏览器</a>，访问本站。';
	message += '</div>';
	$('body').prepend(message);
}

$.browser = {
	mozilla : /firefox/.test(navigator.userAgent.toLowerCase()),
	webkit : /webkit/.test(navigator.userAgent.toLowerCase()),
	opera : /opera/.test(navigator.userAgent.toLowerCase()),
	msie : /msie/.test(navigator.userAgent.toLowerCase())
}








/* 图片上传 */
window.uimg = {
	width:0,
	height:0,
    draw: function(node){
        var uimg = $(node);
		
        window.uimg.make_iframe(uimg);

        uimg.bind("click.uimg", function(){
            var uimg = $(this);
        	window.uimg.width = uimg.data("width")||120;
        	window.uimg.height = uimg.data("height")||120;
            var file = this.uiframe.contents().find("input[type=file]");
            file.bind("change", function(){
                window.uimg_node = uimg;
                file.parents("form:first").submit();
            });
            file.click();
        });
    },
    callback: function(status, json){
		$.crop(json.url, window.uimg.width, window.uimg.height, function(data){
			$.post("/secure/image/scale", {src:json.url,dst:json.url,width:data.canvas_width,height:data.canvas_height}, function(r){
			    $.post("/secure/image/crop", {src:json.url,dst:json.url,width:data.w,height:data.h,left:data.x1,top:data.y1}, function(r){
			        $.post("/secure/image/scale", {src:json.url,dst:json.url,width:data.width,height:data.height}, function(r){	
			            var input_class = window.uimg_node.attr("uimg");
						var input = null;
						if (input_class.indexOf("parent.")==0){
							input = window.uimg_node.parents("form:first").find(input_class.replace("parent.", ""));
						} else {
							input = $(input_class);
						}
						input.val(json.url);
						
						var display_id = window.uimg_node.attr("uimgDisplay");
						var display = null;
						if (display_id.indexOf("parent.")==0){
							display = window.uimg_node.parents("form:first").find(display_id.replace("parent.", ""));
						} else {
							display = $(display_id);
						}
						display.html("<img src='" + json.url +"' width='"+data.width+"' height='"+data.height+"' />");
						
						//恢复form
						window.uimg.make_iframe(window.uimg_node);
				  });
				});
			});
		});
    },
    make_iframe: function(uimg){
        try{$(uimg)[0].uiframe.remove();}catch(e){}
        var url = "/secure/upload/image?callback=parent.window.uimg.callback";
        var iframe = $("<iframe class='uimg_iframe' style='display:none'></iframe>");
        iframe.attr("src", url);
        iframe.attr("frameborder", 0);
        iframe.attr("width", 0);
        iframe.attr("height", 0);
        $(top.document.body).append(iframe);
        $(uimg)[0].uiframe = iframe;
    }
}

$.fn.uimg = function() {
    $.uimg.draw(this);
}

/* 文件上传 */
window.ufile = {
	fcallback:null,
    draw: function(node, fcallback){
        var ufile = $(node);
		window.ufile.fcallback = fcallback;
        window.ufile.make_iframe(ufile);

        ufile.bind("click.ufile", function(){
            var ufile = $(this);
            var file = this.uiframe.contents().find("input[type=file]");
            file.bind("change", function(){
                window.ufile_node = ufile;
                file.parents("form:first").submit();
            });
            file.click();
        });
    },
    callback: function(status, json){
		window.ufile.fcallback(json, window.ufile_node.parent());
		//恢复form
		window.ufile.make_iframe(window.ufile_node);
    },
    make_iframe: function(ufile){
        try{$(ufile)[0].uiframe.remove();}catch(e){}
		var time = new Date().getTime();
        var url = "/secure/upload/blob?callback=parent.window.ufile.callback";
        var iframe = $("<iframe class='ufile_iframe' style='display:none' time='"+time+"'></iframe>");
        iframe.attr("src", url);
        iframe.attr("frameborder", 0);
        iframe.attr("width", 0);
        iframe.attr("height", 0);
        $(top.document.body).append(iframe);
        $(ufile)[0].uiframe = iframe;
    }
}

$.ufile = window.ufile;
$.uimg = window.uimg;

$.crop = function(img, width, height, callback) {
	var time = new Date().getTime();
	var container = $('<div class="container imgcrop">');
	container.append('<img id="photo_'+time+'" src="'+img+'" />');
	container.append('<input type="hidden" id="x1_'+time+'" name=x1 value="0" />');
	container.append('<input type="hidden" id="y1_'+time+'" name=y1 value="0" />');
	container.append('<input type="hidden" id="x2_'+time+'" name=x2 value="0" />');
	container.append('<input type="hidden" id="y2_'+time+'" name=y2 value="0" />');
	container.append('<input type="hidden" id="w_'+time+'" name=w value="0" />');
	container.append('<input type="hidden" id="h_'+time+'" name=h value="0" />');
	container.append('<input type="hidden" name="width" value="'+width+'" />');
	container.append('<input type="hidden" name="height" value="'+height+'" />');
    container.append('<br /><input type="button" class="btn btn-sm btn-primary" value="确定">');
    container.append('<span style="magin-left:10px;"><input type="button" class="closeCropBtn btn btn-sm btn-default" value="取消"></span>');
	container.css({
		position:"absolute",
		width:"auto",
		top:"-10000px",
		left:"-10000px",
		zIndex:9000002
	});
    $("body").append(container);

	var wrapper = $('<div class="wrapper imgcrop">');
	wrapper.css({
		position:"absolute",
		width:$(document).width(),
		height:$(document).height(),
		opacity: "0.8",
		background: "#333",
		top:0,
		left:0,
		filter:"alpha(opacity=80)",
		zIndex:9000000
	});
    $("body").append(wrapper);
    
	

	function preview(img, selection) {
		if (!selection.width || !selection.height){
		    return;
		}else{
		    $('#x1_'+time).val(selection.x1);
		    $('#y1_'+time).val(selection.y1);
		    $('#x2_'+time).val(selection.x2);
		    $('#y2_'+time).val(selection.y2);
		    $('#w_'+time).val(selection.width);
		    $('#h_'+time).val(selection.height);  
		}
	}

	$("#photo_"+time).load(function(){
		container.css({
			marginTop:$(this).height()/1.5*-1,
			marginLeft:$(this).width()/2*-1,
			top:"50%",
			left:"50%"
		});
		// 去掉宽/高约束
		//var imgcrop = $('#photo_'+time).imgAreaSelect({ parent:1, resizable:true, aspectRatio: width+':'+height, x1: 0, y1: 0, x2: width, y2: height , handles: true,
		var imgcrop = $('#photo_'+time).imgAreaSelect({ parent:1, resizable:true, x1: 0, y1: 0, x2: width, y2: height, handles: true,
			fadeSpeed: 200, onSelectChange: preview, minWidth:width, minHeight:height, parent:$(".container.imgcrop") });
		$('#photo_'+time).mousemove();

		container.find(".imgareaselect-border4").dblclick(crop_ok);
		container.find("input[type=button]").click(crop_ok);
		container.find(".closeCropBtn").click(crop_no);
	});
	
	var crop_ok = function(event){
		var data = {img:img};
		container.find("input[name]").each(function(){
			var input = $(this);
			data[input.attr("name")] = input.val();
		});
		data["canvas_width"] = $("#photo_"+time).width();
		data["canvas_height"] = $("#photo_"+time).height();
		
		$(".container.imgcrop").remove();
		$(".wrapper.imgcrop").remove();
		if(callback) callback(data);
	};
  //取消裁剪	
   var crop_no = function(event){
        window.location.reload();
    };
}
/*
usage:
* 
<script src="http://x.ibeiliao.com/file/v2/js/jquery-1.8.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://x.ibeiliao.com/file/v2/js/jquery.imgareaselect-0.9.10/css/imgareaselect-default.css" />
<script type="text/javascript" src="http://x.ibeiliao.com/file/v2/js/jquery.imgareaselect-0.9.10/scripts/jquery.imgareaselect.js"></script>
* 
.container.imgcrop input.btn {border:0;background:#ff4400;padding:8px 20px;font-size:14px;color:#fff;letter-spacing:4px;cursor:pointer;outline:none;margin:10px 0;display:block;border-radius:3px;}
* 
$.crop("http://www.qzwb.com/gb/img/attachement/jpg/site2/20091111/00219b69ab310c6457c717.jpg", "/data.php", 120, 90, function(r){
	alert(r);
});
*/

$(function(){
	
	if ($("textarea.editor").length) {
		var editor = KindEditor.create('textarea.editor', {
			resizeType : 0,
			allowPreviewEmoticons : false,
			allowImageUpload : true,
			uploadJson : '/secure/kindeditor/upload',
            allowFileManager : false,
			afterChange: function(){
				this.sync();
			},
			items : [
				'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
				'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
				'insertunorderedlist', '|', 'emoticons', 'link','image','source']
		});
	}
	
	$(".select-group").each(function(){
		var group = $(this);
		var btn = $("[data-role=item-add]", group);
		var input = $("[data-role=item-input]", group);
		var ul = $("[data-role=list]", group);
		var input_name = group.data("name");
		var handler = group.data("handler");
		btn.unbind("click").bind("click", function(){
			var callback = function(id, title){
				var li = $('<li class="list-group-item clearfix" data-role="item"><span class="glyphicon glyphicon-resize-vertical sort-handle"></span>'+title+'<input type="hidden" name="'+input_name+'"><button class="close delete-btn" data-role="item-delete" type="button" title="删除">×</button></li>');
				if (id){
					li.attr("id", handler+"_"+id);
				}
				li.find("input").val(val);
				ul.append(li);
				input.val("");
			}
			var val = input.val();
			if (val){
				if (handler){
					$[handler](group, input, btn, val, callback);
				} else {
					callback(null, val);
				}
			}
		});
		group.off("click.delete").on("click.delete", "[data-role=item-delete]", function(){
			if (handler){
				$[handler]["delete"](group, $(this).parents("li:first"));
			}
			$(this).parents("li:first").remove();
		});
		if ($.fn.dragsort){
			ul.dragsort({ dragSelector: "li", dragEnd: function() { }, dragBetween: false, placeHolderTemplate: "<li class='list-group-item clearfix' style='background:#f2f3f5'>&nbsp;</li>" });
		}
		if (handler){
			input.unbind("input propertychange").bind("input propertychange", function(e){
				btn.click();
			});
		}
	});

	$["p_search_user"] = function(group, input, btn, val, callback){
		$.post("/searchUser", {instructor:1, keyword:val}, function(json){
			$(".p_search_user_ul").remove();
			if (json&&json.status=="success"&&json.result&&json.result[0]){
				var ul = $("<ul class=p_search_user_ul>");
				ul.css("top", input.offsetParent().top+32);
				ul.css("left", input.offsetParent().left);
				for (var i in json.result){
					var row = json.result[i];
					console.log(row);
					if (!row.avatar){
						row.avatar = "/resources/wangxiaoyun/img/default/avatar.png";
					}
					if (!row.signature){
						row.signature = "";
					}
					var li = $("<li></li>");
					li.append("<span class=avatar><img src='"+row.avatar+"' align=absmiddle></span>");
					li.append("<span class=name>"+row.nickname+"</span>");
					li.append("<span class=signature>"+row.signature+"</span>");
					ul.append(li);
					li[0].data = row;
					li.click(function(){
						var row = this.data;
						if (!$("#p_search_user_"+row.userId).length){
							//var title='<img src="'+(row.avatar||"/wangxiaoyun/img/default/avatar.png?1.5.3")+'" class="avatar-small"> <span class="nickname">'+row.nickname+'</span> <label class="visible-checkbox"> <input type="checkbox" value="1" name="visible_1" checked="checked"> 显示</label>';
						    var title='<img src="'+(row.avatar||"/wangxiaoyun/img/default/avatar.png?1.5.3")+'" class="avatar-small"> <span class="nickname">'+row.nickname+'</span>';
							callback(row.userId, title);
							$.post("/secure/course/"+group.data("courseid")+"/instructor/add", {userId:row.userId, ordered:1}, function(){});
						}
						ul.hide().remove();
					});
				}
				$(group).append(ul);
			}
		}, "json");
	}
	$["p_search_user"]["delete"] = function(group, li){
		var userid = li.attr("id").replace("p_search_user_", "");
		var courseid = group.data("courseid");
		$.post("/secure/course/"+courseid+"/instructor/"+userid+"/remove", {}, function(){});
	}
	
	var video_uploader = $('#course-form');
	if (video_uploader[0] && !video_uploader[0].uploader && $.fn.uploadify){
		video_uploader[0].uploader = video_uploader.find("#upload-picture-btn").uploadify({
			'auto': true,
			'formData': {
				'writetoken' : video_uploader.find("#upload-picture-btn").attr("writetoken"),
				'JSONRPC'     : '{}'
			},
			'buttonText': video_uploader.find("#upload-picture-btn").val(),
			'fileSizeLimit' : '900MB',
			'fileTypeDesc' : '视频文件',
			'width' : video_uploader.find("#upload-picture-btn").outerWidth(),
			'height' : video_uploader.find("#upload-picture-btn").outerHeight(),
			'fileTypeExts' : '*.avi; *.mp4; *.mov',
			'swf'      : '/resources/uploadify/uploadify.swf',
			'uploader' : 'http://v.polyv.net/uc/services/rest?method=uploadfile',
			'onUploadStart' : function(){
				video_uploader.find(".uploadify-queue").show();
				video_uploader.find(".prea").hide();
				$(".uploadify-queue-item .cancel").hide();
			},
			'onUploadSuccess':function(file,data,response){
				data = eval('('+data+')');
				data = data.data[0];
				var vid = data.vid;
				var swf = data.swf_link;
				$(".video_preview").html('<object id="SWFUpload_0" type="application/x-shockwave-flash" data="'+swf+'" width="400" height="280">' +
						'<param name="wmode" value="transparent">' +
						'<param name="movie" value="'+swf+'">' +
						'<param name="quality" value="high"><param name="menu" value="false">' +
						'<param name="allowScriptAccess" value="always">' +
						'<param name="flashvars" value=""></object>');
			}
		});
	}
	$("#upload-picture-btn-button").addClass("btn btn-fat btn-primary").css("padding", "0");
	
	$("input[name=isFree]").each(function(){
		var input = $(this);
		var group = input.parents(".form-group:first").next();
		input.parent().mouseup(function(){
			setTimeout(function(){
				if (input.attr("id")=="freeCourse"&&input[0].checked){
					group.hide();
				} else if (input.attr("id")=="paidCourse"&&input[0].checked) {
					group.show();
				}
			}, 100);
		}).mouseup();
	});

	$("input[name=privacy]").each(function(){
		var input = $(this);
		var group = input.parents(".form-group:first").next();
		input.parent().mouseup(function(){
			setTimeout(function(){
				if (input.attr("id")=="privacyPublic"&&input[0].checked){
					group.hide();
				} else if (input.attr("id")=="privacyPrivate"&&input[0].checked) {
					group.show();
				}
			}, 100);
		}).mouseup();
	});
	
	$("input[name=tickerStatus]").each(function(){
        var input = $(this);
        var group = input.parents(".form-group:first").next();
        input.parent().mouseup(function(){
            setTimeout(function(){
                if (input.attr("id")=="tickerStatusN"&&input[0].checked){
                    group.hide();
                } else if (input.attr("id")=="tickerStatusY"&&input[0].checked) {
                    group.show();
                }
            }, 100);
        }).mouseup();
    });
});

